import React, {
  useState,
  useEffect
} from 'react';
import { withRouter } from 'react-router-dom'
import { Card, Form, Input, Button, Radio, message, Checkbox, Select, InputNumber } from 'antd';
import BreadcrumbBox from '@/components/Base/BreadcrumbBox';
import { checkRules, useDebounceFn, deepclone } from '@/utils'
import { 
  merchantUsdtRecharge, 
  merchantGetRate,
  merchantAccountLike,
  payeeList,
} from '@/api/api'
import './index.scss';

let timeout;
// eslint-disabled-next-line no-unused-vars
const Manage = (props) => {
  const breadcrumbList = ['商户管理', '商户充值']
  const [addForm] = Form.useForm();
  const [rate, setRate] = useState('');
  const [merchant, setMerchant] = useState([]);
  const [payee, setPayee] = useState([]);
  const [payeeInfo, setPayeeInfo] = useState(null);
  
  
  const [data] = useState({  
    "paySettingId": "",
    "merchantId": "",
    "usdtNumbber": "",
    "receiptNumber": "",
    "platformFee": "",
    "remark": "",
    "transPwd": "",
    "rate": "",
    "amount": "",
  })
  // 提交弹框表单做防抖处理
  const submitOk = useDebounceFn((values) => {
    onFinish(values)
  }, 1500, true);
  const onFinish = async (values) => {
    console.log('Success:', values);
    try {
      let params = {
        ...values,
        rate,
      }
      console.log(params)
      let res = await merchantUsdtRecharge(params)
      if (res.code === 0) {
        message.destroy()
        message.success('添加成功')
        addForm.resetFields()
        getPayeeList()
        payee.setFieldsValue({
          "paySettingId": payee.id
        });
        setPayeeInfo(payee[0])
      }
    } catch (error) {
      console.log(error)
    }
  };
  const setUsdtNumbber = (val) => {
    try {
      addForm.setFieldsValue({
        "platformFee": val*payeeInfo.fee*0.01,
        "receiptNumber": (val - val*payeeInfo.fee*0.01),
      });
    } catch(error) {
      console.log(error)
    }
  };
  const handleSearch = () => {
    try {
      merchantAccountLike({
        userName: ''
      }).then(res=>{
        if(res.code === 0) {
          setMerchant(res.data)
        }
      })
    } catch(error) {
      console.log(error)
    }
  };
  
  const getPayeeList = async () => {
    try {
      let res = await payeeList({
        currencyType: 1
      })
      if(res.code === 0) {
        setPayee(res.data)
        if(res.data.length>0){
          addForm.setFieldsValue({
            "paySettingId": res.data[0].id
          });
          setPayeeInfo(res.data[0])
        }
      }
    } catch(error) {
      console.log(error)
    }
  }
  const merchantGetRateHanlder = async () => {
    try {
      let res = await merchantGetRate()
      if(res.code === 0) {
        setRate(res.data)
      }
    } catch(error) {
      console.log(error)
    }
  }
  const onChangeCurrency = (val) => {
    payee.forEach(item=>{
      if(val === item.id){
        setPayeeInfo(item)
        let usdtNumbber = addForm.getFieldValue("usdtNumbber")
        if(usdtNumbber || usdtNumbber===0){
          addForm.setFieldsValue({
            "platformFee": usdtNumbber*item.fee*0.01,
            "receiptNumber": (usdtNumbber - usdtNumbber*item.fee*0.01),
          });
        }
      }
    })
  }
  
   // 初始化
  useEffect(() => {
    getPayeeList()
    handleSearch()
    merchantGetRateHanlder()
    // eslint-disabled-next-line react-hooks/exhaustive-deps
  }, [])
  
  
  return (
    <div className='pass-component'>
      <BreadcrumbBox list={breadcrumbList}></BreadcrumbBox>
      <div className='pass-main'>
        <Card title="添加商户">
          <div className='pass-form'>
            <Form
              name="basic"
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 16 }}
              form={addForm}
              initialValues={data}
              autoComplete="new-password"
              onFinish={submitOk}>
              <Form.Item
                label="货币类型"
                name="paySettingId"
                rules={[
                  { required: true, message: '请选择货币类型' },
                ]}
              >
                <Radio.Group onChange={(e)=>{onChangeCurrency(e.target.value)}}>
                {
                  payee.map((item, i) => (
                    <Radio value={item.id}>{item.currencyName}</Radio>
                  ))
                }
                </Radio.Group>
              </Form.Item>
              <Form.Item
                label="货币汇率"
              >
                <span>1USDT = {rate || '--'}币</span>
              </Form.Item>
              <Form.Item
                label="充值商户"
                name="merchantId"
                rules={[
                  { required: true, message: '请选择充值商户' },
                ]}
              >
                <Select 
                  optionFilterProp="label"
                  showSearch
                  options={merchant.map((item) => ({ label: item.userName, value: item.id }))}
                />
              </Form.Item>
              <Form.Item
                label="USDT数量"
                name="usdtNumbber"
                rules={[
                  { required: true, message: '请输入USDT数量!' },
                ]}
              >
                <InputNumber style={{width: '100%'}} onChange={setUsdtNumbber} />
              </Form.Item>
              <Form.Item
                label="到账币数"
                name="receiptNumber"
              >
                <Input disabled={true} />
              </Form.Item>
              <Form.Item
                label="手续费率"
              >
                {payeeInfo&&(payeeInfo.fee||payeeInfo.fee===0) ? payeeInfo.fee : '--'}%
              </Form.Item>
              <Form.Item
                label="手续费"
                name="platformFee"
              >
                <Input disabled={true} />
              </Form.Item>
              <Form.Item
                label="备注说明"
                name="remark"
                rules={[
                  { required: true, message: '请输入备注说明' },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="交易密码"
                name="transPwd"
                rules={[
                  { required: true, message: '请输入新密码!' },
                ]}
              >
                <Input.Password />
              </Form.Item>
              <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
                <Button type="primary" htmlType="submit">
                  提交
                </Button>
              </Form.Item>
            </Form>
          </div>
        </Card>
      </div>
    </div>
  )
}
export default withRouter(Manage)